#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@Author:    Colin
@Github:    https://github.com/opscolin
@Gitee:     https://gitee.com/colin5063
@DateTime:  2022/9
@File:      config.py
@Software:  PyCharm
"""


from flask import Flask, Response, request
from prometheus_client.core import CollectorRegistry
from prometheus_client import generate_latest, Gauge

import utils
import pushgateway
app = Flask(__name__)


# -------------------- 定义 metric 采集函数 -------------------- #
def metric_rds_variables(instance_name, registry):
    cfg = utils.get_config('metrics.yml')
    for metric_type in cfg.keys():
        for metric in cfg[metric_type].keys():
            value = utils.get_mysql_variable_values(instance_name, metric_type, metric)[0][1]
            desc = cfg[metric_type][metric]
            if desc:
                metric_desc = desc
            else:
                metric_desc = metric

            metric_name = f'{instance_name}_{metric}'
            g = Gauge(f'mysql_global_{metric_type}_{metric}', metric_desc, ['instance_name'], registry=registry)
            g.labels(instance_name=instance_name).set(float(value))


@app.route('/scrape')
def main():
    target = request.args.get("target")
    registry = CollectorRegistry(auto_describe=False)
    metric_rds_variables(target, registry)
    return Response(generate_latest(registry), mimetype='text/plain')


@app.route('/push/rds')
def push_rds():
    """rds cpu/memory/iops ; 每分钟采集一次"""
    instance_name = request.args.get("target")
    registry = CollectorRegistry(auto_describe=False)
    # pushgateway.metric_rds_disk_usage(instance_name, registry)
    # pushgateway.metric_rds_cpu_mem(instance_name, registry)
    # pushgateway.metric_rds_iops(instance_name, registry)
    pushgateway.metric_rds(instance_name, registry)
    return Response("Push success")


@app.route('/push/rds/disk')
def push_rds_disk():
    """每半个小时采集一次"""
    instance_name = request.args.get("target")
    registry = CollectorRegistry(auto_describe=False)
    pushgateway.metric_rds_disk_usage(instance_name, registry)
    return Response("Push RDS Disk success")

@app.route('/push/size/table')
def push_tablesize():
    instance_name = request.args.get("target")
    dbname = request.args.get("dbname")
    tablename = request.args.get("tablename")
    registry = CollectorRegistry(auto_describe=False)
    pushgateway.metric_rds_tablesize(instance_name, dbname, tablename, registry)
    return Response("Push TableSize success")


@app.route('/push/size/db')
def push_dbsize():
    instance_name = request.args.get("target")
    dbname = request.args.get("dbname")
    registry = CollectorRegistry(auto_describe=False)
    pushgateway.metric_rds_dbsize(instance_name, dbname, registry)
    return Response("Push DbSize success")


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5005)
